#include "snake.h"
int load_data(FILE *file, Game *game);
char buf[0x100];
const char *filename = ".config";
char *prompt = "Enter the width, height and score of the game (separated by spaces): ";
char *data_type[] = {"Delay", "Width", "Height"};
int data[sizeof(data_type) / sizeof(data_type[0])];
int i = 0;
int load_game(Game *game)
{

    FILE *file = fopen(filename, "r");
    if (file)
        return load_data(file, game);
    // generating .config file if it doesn't exist
    game->delay = 10;
    game->width = 40;
    game->height = 20;
    file = fopen(filename, "w");
    if (!file)
    {
        fprintf(stderr, "Error: Cannot open config file for writing\n");
        return 1;
    }
    fprintf(file, "Delay\tWidth\tHeight\n");
    fprintf(file, "%d\t\t%d\t\t%d\n", game->delay, game->width, game->height);
    fclose(file);
    return 0;
}
int load_data(FILE *file, Game *game)
{
    if (!file)
        return 1;
    while (!feof(file)) // trying to find the correct data in the file
    {
        // reading pauses after each spaced input
        fscanf(file, "%s", buf);
        if (sscanf(buf, "%d", data + i) == 0)
            continue;
        printf("Found %s: %d\n", data_type[i], data[i]);
        i++;
        if (i <= sizeof(data_type) / sizeof(data_type[0]))
            continue;
        // if all data is found, break the loop
        game->delay = data[0];
        game->width = data[1];
        game->height = data[2];
        fclose(file);
        return 0;
    }
    fprintf(stderr, "Error: Invalid data in config file\n");
    fclose(file);
    return 1;
}